package com.example.ex.ws;



import com.example.ex.mapper.ChatMessageMapper;
import com.example.ex.entity.Message;
import com.example.ex.pojo.ChatMessage;
import com.example.ex.pojo.LoginUser;
import com.example.ex.utils.MessageUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@RestController
@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfigurator.class)
@Component
public class ChatEndpoint {

    private static ChatMessageMapper chatMessageMapper;

    @Autowired
    public void setChatMessageMapper(ChatMessageMapper chatMessageMapper) {
        ChatEndpoint.chatMessageMapper = chatMessageMapper;
    }

    //用来存储每个用户客户端对象的ChatEndpoint对象
    private static Map<String, ChatEndpoint> onlineUsers = new ConcurrentHashMap<>();

    //声明session对象，通过对象可以发送消息给指定的用户
    private Session session;

    //声明HttpSession对象，我们之前在HttpSession对象中存储了用户名
    private HttpSession httpSession;
    private String fromName;



    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        this.session = session;
        HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
//        this.httpSession = httpSession;
        if (httpSession == null) {
            // 如果 HttpSession 为空，说明用户刷新页面后建立了新的会话，此时需要从 WebSocket Session 中取出存储的用户信息
            String username = (String) session.getUserProperties().get("user");
            if (username == null) {
                // 用户信息不存在，不能建立会话
                return;
            }
            this.fromName = username;
            onlineUsers.put(username, this);
        } else {
            // 原始的 HttpSession 存在，保存登陆的对象
            String username = (String) httpSession.getAttribute("user");
            fromName = username;
            onlineUsers.put(username, this);
        }

        //将当前在线用户的用户名推送给所有的客户端
        String message = MessageUtils.getMessage(true, null, getNames(), 1);
        broadcastAllUsers(message);
    }


    private void broadcastAllUsers(String message) {
        try {
            for (Map.Entry<String, ChatEndpoint> entry : onlineUsers.entrySet()) {
                String name = entry.getKey();
                ChatEndpoint chatEndpoint = entry.getValue();
                System.out.println("向用户 " + name + " 推送消息：" + message);
                if (chatEndpoint.session.isOpen()) {
                    chatEndpoint.session.getBasicRemote().sendText(message);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //返回在线用户名
    private Set<String> getNames() {
        return onlineUsers.keySet();
    }

    //收到消息
    @OnMessage
    public void onMessage(String message, Session session) {
        //将数据转换成对象
        try {
            System.out.println("来传输数据了");
            ObjectMapper mapper = new ObjectMapper();
            Message mess = mapper.readValue(message, Message.class);
            String toName = mess.getToName();
            String data = mess.getMessage();
            String username = fromName;
            System.out.println(username);
            int code = mess.getCode();
            if(data != "")
            {
                String resultMessage = MessageUtils.getMessage(false, username, data, code);
                //发送数据
                onlineUsers.get(toName).session.getBasicRemote().sendText(resultMessage);
                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setReceivername(toName);
                chatMessage.setSendername(fromName);
                chatMessage.setContext(data);
                chatMessage.setCode(code);
                System.out.println(chatMessageMapper.insert(chatMessage) > 0 ? "插入成功！" : "插入失败！");
                System.out.println(resultMessage);
            }
        } catch (Exception e) {
            System.out.println("传递数据出错啦");
            e.printStackTrace();
        }

    }

    @OnClose
    public void onClose(Session session) {
        if (httpSession != null) {
            String username = (String) httpSession.getAttribute("user");
            System.out.println("离线用户：" + username);
            if (username != null) {
                onlineUsers.remove(username);
            }
            // 移除 HttpSession 中的用户信息
            httpSession.removeAttribute("user");
            String message = MessageUtils.getMessage(true, null, getNames(), 1);
            broadcastAllUsers(message);
        }
        onlineUsers.remove(fromName);
        String message = MessageUtils.getMessage(true, null, getNames(), 1);
        broadcastAllUsers(message);
    }

}